package com.hxzy.controller;

import com.hxzy.pojo.Book;
import com.hxzy.pojo.Cart;
import com.hxzy.pojo.CartItem;
import com.hxzy.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zl
 * @create 2020-11-03 15:08
 */
@Controller
public class CartController {
    @Autowired
    private BookService bookService;

    @RequestMapping("/addCart")
    public String addCart(@RequestParam("id")Integer id, HttpServletRequest req, @RequestHeader("referer")String referer){
        Book book = bookService.selectBookById(id);
        CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice(), book.getPrice());
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            req.getSession().setAttribute("cart", cart);
        }
        cart.addCartItem(cartItem);
        req.getSession().setAttribute("lastName",cartItem.getName());
        return "redirect:" + referer;
    }
    @RequestMapping("/deleteItem")
    public String deleteItem(@RequestParam("id")Integer id, HttpServletRequest req, @RequestHeader("referer")String referer){
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null){
            cart.deleteCartItemById(id);
        }
        return "redirect:" + referer;
    }
    @RequestMapping("/clear")
    public String clear(HttpServletRequest req, @RequestHeader("referer")String referer){
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null){
            cart.clear();
        }
        return "redirect:" + referer;
    }
    @RequestMapping("/updateCart")
    public String updateCart(@RequestParam("id")Integer id,@RequestParam("count")Integer count,HttpServletRequest req, @RequestHeader("referer")String referer){
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null){
            cart.updateCartItem(id,count);
        }
        return "redirect:" + referer;
    }
}
